<template>
    <div>
        <div v-if="mode === 'DESIGN'">
            <!--组件在设计器中的样子-->
            <el-button type="primary" style="width: 200px;" plain v-if="iSSelect==1" @click="show">{{ $t(buttonName) }}</el-button>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" disabled @blur="show" v-else-if="iSSelect==2"></el-input>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" readonly disabled @blur="show" v-else>
                <template #append >
                    <el-button @click="show" >{{ $t(buttonName) }}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else-if="mode === 'PC' && !readonly">
            <!--组件在PC端预览及真实显示的样子-->
            <el-button type="primary" plain style="width: 200px;" v-if="iSSelect==1" @click="show">{{ $t(buttonName) }}</el-button>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show"   @blur="show" v-else-if="iSSelect==2"></el-input>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" readonly @blur="show" v-else>
                <template #append >
                    <el-button @click="show" >{{ $t(buttonName) }}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else-if="mode === 'MOBILE' && !readonly">
            <!--组件在移动端预览及真实显示的样子-->
            <el-button type="primary" plain style="width: 200px;" v-if="iSSelect==1" @click="show">{{ $t(buttonName) }}</el-button>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" disabled @blur="show" v-else-if="iSSelect==2"></el-input>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" disabled @blur="show" v-else>
                <template #append >
                    <el-button @click="show" >{{ $t(buttonName) }}</el-button>
                </template>
            </el-input>
        </div>
        <div v-else>
            <!--组件在流程实例预览中，只读状态下样子-->
            <el-button type="primary" plain style="width: 200px;" v-if="iSSelect==1" @click="show">{{ $t(buttonName) }}</el-button>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show"  @blur="show" v-else-if="iSSelect==2"></el-input>
            <el-input v-model="_value" :placeholder="$t(placeholder)" @keyup.enter.native="show" readonly  @blur="show" v-else>
                <template #append >
                    <el-button @click="show" >{{ $t(buttonName) }}</el-button>
                </template>
            </el-input>
        </div>
    </div>
</template>

<script>
//混入配置
import componentMinxins from '../ComponentMinxins'
import { ElNotification } from 'element-plus'
export default {
    mixins: [componentMinxins],
    name: "TextSelector",
    components: {},
    props: {
        modelValue: {
            type: String,
        },
        buttonName: {
            type: String,
            default: 'webAuto.sure',
        },
        placeholder: {
            type: String,
            default: 'webAuto.selectOption',
        },
        defaultValue: {
            type: String,
        },
        expanding: {
            type: Boolean,
            default: false,
        },
        popUpBox: {
            type: Boolean,
            default: false,
        },
        iSSelect: {
            type: Boolean,
            default: false,
        },
        dataSource: {
            type: String,
            default: '',
        },
        formData: {
            type: Object,
            default: () => {
                return {}
            }
        },
        optionText: {
            type: Array,
            default: () => {
                return []
            }
        },
        http: {
            type: Object,
            default: () => {
                return {
                    url: null,
                    method: 'GET',
                    headers: [],
                    contentType: 'JSON',
                    params: [],
                    data: null,
                    preHandler: null,
                    aftHandler: {
                        isJs: false,
                        js: '',
                        rule: {
                            source: '',
                            name: '',
                            value: ''
                        }
                    },
                }
            }
        },
    },
    data() {
        return {
            loading: false,
            visible: false,
            keywordSelect: '',
            headerDate: [],
            tableData: [], // 表格绑定数据
            pageSize: 15, // 分页的
            total: 0,
            currentPage: 1,
            rowLis: [], // 选择行的数据
            small: false,
            background: false,
            preHandlerFuc: null,
            aftHandlerFuc: null,
            disabled: false,
            lineNo: '',
        }
    },
    computed: {
        _value: {
            get() {
                return this.modelValue
            },
            set(val) {
                this.$emit('update:modelValue', val)
            },
        },
        formItems() {
            return this.$store.state.design.formItems
        },
        formMap() {
            const map = new Map();
            this.itemToMap(this.formItems, map)
            return map
        },
    },
    mounted() {
        // 回显已选中的行
        this.$nextTick(() => {
            this.rowLis.forEach(row => {
                this.$refs.multipleTable.toggleRowSelection(row, true);
            });
        });
    },
    methods: {
        // 判断数组中包含某个不确定的对象
        containsObject(array, object) {
            return array.some(item => {
                for (let key in object) {
                    if (item[key] !== object[key]) {
                        return false;
                    }
                }
                return true;
            });
        },
        // id标识长度5位
        generateUniqueId(length = 5) {
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            const charactersLength = characters.length;
            for (let i = 0; i < length; i++) {
                result += characters.charAt(Math.floor(Math.random() * charactersLength));
            }
            return result;
        },
        // 是否显示弹框
        show() {
            // 是否选择 进行判断调用接口
            if(this.iSSelect==3){
                this.doRequest()
            }else{
                this.doRequest()
            }
        },
        doRequest() {
            this.headerDate = []
            if (this.http.url && this.http.method) {
                const params = {
                    url: this.http.url,
                    method: this.http.method.toLowerCase(),
                    headers: {
                        'Content-Type': this.http.contentType === 'JSON' ? 'application/json' : 'application/x-www-form-urlencoded',
                        'Wflowtoken': localStorage.getItem('wflow-token'),
                        ...this.coverParams(this.http.headers || [])
                    },
                    formData: Object.assign({}, this.formData),
                    params: this.coverParams(this.http.params || []), //查询条件
                    data: this.http.contentType === 'JSON' ? JSON.parse(this.bindVar(this.http.data || '{}')) : ''
                }
                // params.params.value = this.keywordSelect   //表格自定义的查询条件 关键字查询
                // params.params.pageSize = this.pageSize //分页 第几页
                // params.params.pageNo = this.currentPage  //分页 每页条数
                this.preHandler(params, this.http.preHandler)
                //这里由于前置处理后，可能修改params参数，所以需要重新处理
                if (this.http.contentType !== 'JSON') {
                    params.data = this.coverParams(params.params, true)
                    params.params = {} //去除参数，防止参数跑到url中
                }
                this.loading = true
                this.$axios.request(params).then(rsp => {
                    // 接口返回数据赋值给表格，自定义处理了，就没有后置处理

                    // 是否回显页面字段
                    if (this.optionText.length > 0) {
                        this.formData[this.optionText[0].value] = rsp.data.msg ||this.defaultValue||'还未有被他流程使用，没有重复！！！'
                    }
                    // 是否弹框提示信息
                    if (this.popUpBox &&rsp.data.msg) {
                        this.$message.warning( rsp.data.msg)
                    }

                }).catch(err => {
                    this.loading = false
                    this.$message.warning(this.$t('webAuto.RequestSource') + JSON.stringify(err))
                })
            }
        },
        //前置处理
        preHandler(params, script) {
            if (!this.preHandlerFuc) {
                this.preHandlerFuc = new Function('ctx', `${script}\n preHandler(ctx)`)
            }
            try {
                this.preHandlerFuc(params)
            } catch (e) {
                // console.log(e)
            }
        },
        bindVar(str) {
            return str.replace(/\$\{(\w+)\}/g, (match, key) => {
                return this.formData[key] || '';
            })
        },
        //数组转对象
        coverParams(args, isForm = false) {
            let params = {};
            if (Array.isArray(args)) {
                args.forEach(arg => {
                    if (this.$isNotEmpty(arg.name)) {
                        params[arg.name] = arg.value.replace(/\$\{(\w+)\}/g, (match, key) => {
                            // 特殊处理 ${lang}
                            if (key === 'lang') {
                                return localStorage.getItem('lang')?.includes('中文') ? 'zh-CN' : localStorage.getItem('lang')?.includes('English') ? 'en-US' : 'es-MX';
                            }
                            return this.formData[key] || '';
                        })
                    }
                })
            } else {
                params = { ...args }
            }
            if (isForm) {
                return Object.keys(params).map(v => `${encodeURIComponent(v)}=${encodeURIComponent(params[v])}`).join('&')
            }
            return params
        }
    }

}
</script>

<style scoped>
.demo-pagination-block {
    height: 40px;
    width: 100%;
    margin-top: 8px;
    box-sizing: border-box;
    font-size: 12px;
    background-color: #faf8f8;
    overflow: hidden;
}

.dialog {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    height: 500px;
}

.el-select .el-select--default {
    width: 100px !important;
}

::v-deep .el-table__body tr.current-row>td {
    color: #fff;
    background: #e69346 !important;
}
</style>